<script setup lang="ts">
import { useSendMobileCode } from '@/composable'
import router from '@/router'
import { loginByMobile, loginByPassword } from '@/services/user'
import { useUserStore } from '@/stores'
import type { User } from '@/types/user'
import { codeRules, mobileRules, passwordRules } from '@/utils/rules'
import { showSuccessToast, showToast } from 'vant'

import { ref } from 'vue'
import { useRoute } from 'vue-router'

const mobile = ref('13230000027')
const password = ref('abc12345')
const agree = ref(false)
// 是密码登录还是验证码登录
const isPass = ref(true)

// 补充说明：只要能够进入 login 函数，那么表单校验一定是通过了
const login = async () => {
  if (!agree.value) return showToast('请勾选我已同意')
  // #region 发请求
  // useUserStore().saveUser(await loginByPassword(mobile.value, password.value))
  let user: User | null = null

  if (isPass.value) {
    user = await loginByPassword(mobile.value, password.value)
  } else {
    user = await loginByMobile(mobile.value, code.value)
  }

  // const user = isPass.value
  //   ? await loginByPassword(mobile.value, password.value)
  //   : await loginByMobile(mobile.value, code.value)

  const userStore = useUserStore()
  userStore.saveUser(user)
  // #endregion

  showSuccessToast('登录成功')

  // #region 登录成功跳转逻辑
  const { returnUrl } = router.currentRoute.value.query
  // 判断是否有回跳地址
  // if (returnUrl) {
  //   // 说明有回跳地址
  //   router.push(returnUrl as string)
  // } else {
  //   // 跳个人中心
  //   router.push({ name: 'UserIndex' })
  // }
  router.replace((returnUrl as string) || { name: 'UserIndex' })
  // #endregion
}

const { refForm, time, send, code } = useSendMobileCode(mobile, 'login')

// 是否显示密码
const showPassword = ref(false)

const route = useRoute()
const qqLogin = () => {
  /* global QC */
  const url = QC.Login.insertButton._getPopupUrl({
    appId: '102015968',
    redirectURI:
      import.meta.env.VITE_CP_QQ_LOGIN_BACK_URL +
      'login/callback?returnUrl=' +
      (route.query.returnUrl || '')
  })
  window.location.href = url
}
</script>

<template>
  <div class="login-page">
    <cp-nav-bar
      right-text="注册"
      @click-right="$router.push({ name: 'RegisterIndex' })"
    ></cp-nav-bar>
    <!-- 头部 -->
    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPass = !isPass">
        <span>{{ isPass ? '短信验证码登录' : '密码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <!-- submit 触发时机：所有的表单单项都校验通过后，才会触发submit事件，执行到login函数 -->
    <van-form ref="refForm" autocomplete="off" @submit="login">
      <van-field
        v-model="mobile"
        name="mobile"
        :rules="mobileRules"
        placeholder="请输入手机号"
        type="tel"
      ></van-field>
      <van-field
        v-if="isPass"
        v-model="password"
        :rules="passwordRules"
        placeholder="请输入密码"
        :type="showPassword ? 'text' : 'password'"
      >
        <template #button>
          <cp-icon
            @click="showPassword = !showPassword"
            :name="`login-eye-${showPassword ? 'on' : 'off'}`"
          ></cp-icon>
        </template>
      </van-field>
      <van-field
        v-else
        v-model="code"
        :rules="codeRules"
        placeholder="短信验证码"
      >
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">
            {{ time > 0 ? `${time}s后再次发送` : '发送验证码' }}
          </span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <!-- native-type 表明按钮原生类型，必须加上后才能触发所在表单的 submit 事件 -->
        <van-button block type="primary" native-type="submit">登 录</van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <div class="icon" @click="qqLogin">
        <img src="@/assets/qq.svg" alt="" />
      </div>
    </div>
  </div>

  <itcast-card header="标题" :body-style="{ color: 'red' }" :shadow="'hover'">
    <template #header> 卡片标题 </template>
    卡片内容
  </itcast-card>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
